package smecta.client.print.controller;

import javafx.fxml.FXML;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import smecta.client.print.common.constants.LoginConstant;
import smecta.client.print.domain.SysUser;
import smecta.client.print.mapper.SysUserMapper;
import smecta.client.print.service.cache.biz.LoginInfoCacheService;
import smecta.client.print.util.AlertUtil;

import java.util.Date;
import java.util.List;

@Component
public class ChangePasswordController {

    @Autowired
    private SysUserMapper sysUserMapper;

    @FXML
    private TextField newPasswordField;

    @FXML
    private TextField confirmNewPasswordField;

    @FXML
    private void handleConfirm() {
        String newPassword = newPasswordField.getText();
        String confirmNewPassword = confirmNewPasswordField.getText();

        if (StringUtils.isEmpty(newPassword)) {
            AlertUtil.info("新密码不能为空!");
            return;
        }

        if (StringUtils.isEmpty(confirmNewPassword)) {
            AlertUtil.info("确认新密码不能为空!");
            return;
        }

        if (!StringUtils.equals(newPassword, confirmNewPassword)) {
            AlertUtil.info("两次密码输入不一致!");
            return;
        }

        if (updateNewPassWord(newPassword)) {
            AlertUtil.info("修改成功!");
            Stage stage = (Stage) newPasswordField.getScene().getWindow();
            stage.close();

        } else {
            AlertUtil.error("密码更改失败!");
        }
    }

    @FXML
    private void handleCancel() {
        Stage stage = (Stage) newPasswordField.getScene().getWindow();
        stage.close();
    }

    private boolean updateNewPassWord(String newPassword) {
        String userName = LoginInfoCacheService.instance.get(LoginConstant.USER_NAME_CACHE_KEY);
        if (StringUtils.isEmpty(userName)) {
            return false;
        }
        SysUser sysUser = new SysUser();
        sysUser.setUserName(userName);
        List<SysUser> users = sysUserMapper.selectSysUserList(sysUser);
        if (CollectionUtils.isNotEmpty(users)) {
            users.stream().forEach(item -> {
                item.setPassword(newPassword);
                item.setUpdateTime(new Date());
                sysUserMapper.updateSysUser(item);
            });
        }
        return true;
    }
}
